//
//  ViewController.m
//  SocialCell
//
//  Created by student10 on 2020/11/22.
//  Copyright © 2020 student10. All rights reserved.
//

#import "GroundViewDemo.h"
#import "SocialTagListView.h"
#import "SocialCell.h"
#import "Masonry.h"
#import "HomeViewDemo.h"
#import "CommentViewController.h"
#import "AppDelegate.h"

@interface GroundViewDemo () <UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate>

@property (nonatomic, strong) NSArray<NSString *> *objects;
@property (nonatomic, strong) NSMutableArray * tagList;
@property (nonatomic, strong) NSMutableArray * userName;
@property (nonatomic, strong) NSMutableArray<NSArray *> *imageURL;
@property (nonatomic, strong) NSMutableArray *LikeNum;
@property (nonatomic, strong) NSMutableArray *CommentNum;
@property (nonatomic, strong) NSMutableArray *Time;
@property (nonatomic, strong) NSMutableArray *contentID;
@property (nonatomic, strong) NSMutableArray *userID;
@property (nonatomic, strong) NSMutableArray *resultIndex;

@end

@implementation GroundViewDemo

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];

    UITextField *search = [[UITextField alloc]initWithFrame:CGRectMake(0, 0, self.navigationController.navigationBar.frame.size.width*0.4, self.navigationController.navigationBar.frame.size.height*0.5)];
    search.placeholder = @"搜索框";
    search.borderStyle = UITextBorderStyleRoundedRect;
    self.navigationItem.titleView = search;
    search.delegate = self;
    [search mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.left.mas_equalTo(10);
        make.height.mas_equalTo(80);
        }];
    
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectZero];
    tableView.delegate = self;
    tableView.dataSource = self;
    // 步骤1：
    tableView.rowHeight = UITableViewAutomaticDimension;
    // 步骤2：
    tableView.estimatedRowHeight = 100.0;
    [self.view addSubview:tableView];

    if (@available(iOS 11.0, *)) {
        // https://www.jianshu.com/p/b616bea9da88
        tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentAlways;
    }

    [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
        // 搜索响应
    [textField resignFirstResponder];
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"搜索" message:@"检索完成" preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"了解" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self SearchData: textField.text];
        NSMutableArray *searchContent = [NSMutableArray array];
        NSMutableArray *searchTag = [NSMutableArray array];
        NSMutableArray *searchName = [NSMutableArray array];
        NSMutableArray *searchLikeNum = [NSMutableArray array];
        NSMutableArray *searchCommentNum = [NSMutableArray array];
        NSMutableArray *searchTime = [NSMutableArray array];
        NSMutableArray *searchContentID = [NSMutableArray array];
        NSMutableArray *searchUserID = [NSMutableArray array];
        NSMutableArray<NSArray *> *searchImage = [NSMutableArray<NSArray *> array];
        
        for(int i = 0; i < [self.resultIndex count]; i++){
            int index = [self.resultIndex[i] intValue];
            [searchContent addObject: self.objects[index]];
            [searchTag addObject: self.tagList[index]];
            [searchName addObject:self.userName[index]];
            [searchImage addObject: self.imageURL[index]];
            [searchLikeNum addObject: self.LikeNum[index]];
            [searchCommentNum addObject: self.CommentNum[index]];
            [searchTime addObject:self.Time[index]];
            [searchContentID addObject:self.contentID[index]];
            [searchUserID addObject:self.userID[index]];
        }
        // 切换视图
        if (self.resultIndex.count == 0) {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"搜索完毕" message:@"没有找到相关内容" preferredStyle:UIAlertControllerStyleAlert];
            [alert addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:nil]];
             [self presentViewController:alert animated:YES completion:nil];
        } else {
            HomeViewDemo *searchView = [[HomeViewDemo alloc]init];
            [searchView InitData:searchContent tagList:searchTag userName: searchName image: searchImage LikeNum:searchLikeNum CommentNum:searchCommentNum Time:searchTime ContentID:searchContentID ];
            searchView.canEdit = NO;
            [self.navigationController pushViewController:searchView animated:YES];
        }
        return;
    }]];
    [self presentViewController:alert animated:YES completion:nil];
    return YES;
}

- (void) SearchData:(NSString *)input{
    self.resultIndex = [NSMutableArray array];
    //NSMutableArray *index = [NSMutableArray array];
    for(int i = 0; i < [self.objects count]; i++){
        // 根据detail搜索
        if([self.objects[i] containsString: input]){
            NSString *temp = [NSString stringWithFormat:@"%d",i];
            if(![self.resultIndex containsObject: temp]){
                [self.resultIndex addObject:temp];
            }
            //NSLog(@"Yes detail Find");
        }
        // 根据标签搜索
        if([self.tagList[i] containsObject: input]){
            NSString *temp = [NSString stringWithFormat:@"%d",i];
            if(![self.resultIndex containsObject: temp]){
                [self.resultIndex addObject:temp];
            }
            //NSLog(@"Yes tag Find");
        }
    }
//    for(id i in self.resultIndex){
//        NSLog(@"%@", i);
//    }
    NSLog(@"搜索到%lu个结果", [self.resultIndex count]);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITableViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    //NSLog(@"currentMode2 = %@", [NSRunLoop currentRunLoop].currentMode);
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"%@ %@",self.contentID[indexPath.row], self.userID[indexPath.row]);
    CommentViewController *VC = [[CommentViewController alloc] initWithContentID:self.contentID[indexPath.row] andUserID:self.userID[indexPath.row]];
    [VC setHidesBottomBarWhenPushed:YES];
    [self.navigationController pushViewController:VC animated:YES];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.objects.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellID = @"CellID";
    SocialCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (cell == nil) {
        NSMutableArray *tagList = [NSMutableArray array];
        for(id i in self.tagList[indexPath.row]){
            NSString *temp = i;
            NSLog(@"%@", temp);
            [tagList addObject:temp];
        }
        AppDelegate *myDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        cell = [[SocialCell alloc] initWithPicnum: [self.imageURL[indexPath.row] count] andCanEdit:NO andHasLike:[myDelegate.haveLikeContentList containsObject:self.contentID[indexPath.row]] andTagList:tagList];
    }
    cell.contentID = self.contentID[indexPath.row];
    [cell.avatarButton setImage:[UIImage imageNamed:@"an.jpg"] forState:UIControlStateNormal];
    cell.nicknameLabel.text = self.userName[indexPath.row];
    
    NSString *timeTemp = [[NSString alloc]initWithFormat: @"%@", self.Time[indexPath.row]];
    cell.timeLabel.text = [self TimeProcessing:timeTemp];
    
    cell.contentLabel.text = self.objects[indexPath.row];
    //NSLog(@"%ld", indexPath.row);

    int count = 0;
    for(id i in self.imageURL[indexPath.row]){
        NSString *temp = [[NSString alloc]initWithFormat: @"http://172.18.178.56/api/thumb/%@", i];
        NSURL *imageURL = [NSURL URLWithString:temp];
        NSURLSessionDataTask *task = [NSURLSession.sharedSession dataTaskWithURL:imageURL completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            if (error == nil) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [((UIImageView*)cell.picArray[count]) setImage:[UIImage imageWithData:data]];
                });
            }
        }];
        [task resume];
        
        /*
        NSString *temp = [[NSString alloc]initWithFormat: @"http://172.18.178.56/api/thumb/%@", i];
        NSURL *imageURL = [NSURL URLWithString:temp];
        NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
        ((UIImageView*) cell.picArray[count]).image = [UIImage imageWithData:imageData];
        */
        count++;
    }
    
    //NSLog(@"like -----%@",self.LikeNum[indexPath.row]);
    NSString *temp = [[NSString alloc]initWithFormat: @"%@", self.LikeNum[indexPath.row]];
    cell.likeCountLabel.text = temp;
    temp = [[NSString alloc]initWithFormat: @"%@", self.CommentNum[indexPath.row]];
    cell.commentCountLabel.text = temp;
//    cell.commentlabel.text = @"aaaaaaaaaaaa";
    
    return cell;
}

- (NSString *) TimeProcessing: (NSString *)timeString{
    
    NSString *timestamp = timeString;
    NSString *timestamp2 = [timestamp stringByReplacingOccurrencesOfString:@"000" withString:@""];
    //NSLog(@"%@",timestamp2);
    NSDate *timeData = [NSDate dateWithTimeIntervalSince1970:[timestamp2 intValue]];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy年MM月dd日 HH:mm"];
    NSString *strTime = [dateFormatter stringFromDate:timeData];
    return strTime;
}

- (void)sss:(id)sender {
    //NSLog(@"sssss");
}

- (void)InitData:(NSMutableArray *)detail tagList:(NSMutableArray *)tagList userName:(NSMutableArray *)userName image:(NSMutableArray<NSArray *> *)image LikeNum:(NSMutableArray *)LikeNum CommentNum:(NSMutableArray *)CommentNum Time:(NSMutableArray *)Time ContentID:(NSMutableArray *)contentID UserID:(NSMutableArray *)userID
{
    self.objects = detail;
    self.tagList = tagList;
    self.userName = userName;
    self.imageURL = image;
    self.LikeNum = LikeNum;
    self.CommentNum = CommentNum;
    self.Time = Time;
    self.contentID = contentID;
    self.userID = userID;
    //NSLog(@"%@", self.objects);
}
@end

